package com.jdk.learn.juc._05thread;

import java.util.concurrent.*;

/**
 * Created by ricky
 * on 2018/1/31.
 * 创建线程有四种
 * 1。通过继承thread
 * 2.  实现runnable
 * 3. callable
 * 4. 通过线程池
 */
public class TestCreateThreadWay {

    public static void main(String[] args) {

        //通过thread创建线程
        ThreadDemo threadDemo=new ThreadDemo("测试线程");
        threadDemo.start();

        RunableDemo runableDemo=new RunableDemo();
        new Thread(runableDemo).start();

        CallableDemo cd=new CallableDemo();
        FutureTask<Object> ft=new FutureTask<Object>(cd);
        new Thread(ft).start();
        try {
            System.out.println(ft.get().toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //线程池
        ExecutorService executorService= Executors.newFixedThreadPool(2);//创建2个线程
        Future<String> future = executorService.submit(() -> {
            return "线程池方式结束了";
        });
        try {
            System.out.println(future.get().toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        executorService.shutdown();
        executorService=null;//擦除引用 进行线程池回收
    }
}

/**
 * 通过thread创建线程
 */
class  ThreadDemo extends Thread{
    private String name;
    public ThreadDemo(String name) {
        this.name=name;
    }

    @Override
    public void run() {
        System.out.println("thread方式执行run方法");
    }
}

/**
 * 通过runnable创建线程
 */
class RunableDemo implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable方式执行run方法");
    }
}

/**
 * 通过Callable创建线程
 * 区别是有返回值 且可以抛出异常
 * 需要fucturetask的支持
 */
class CallableDemo implements Callable<Object>{
    @Override
    public Object call() throws Exception{
        System.out.println("Callable方式执行run方法");
        return "返回值";
    }
}

/**
 * 线程池
 */
class poolDemo {

}
